import json
import re
import sys
from configparser import ConfigParser
from openpyxl import load_workbook

if __name__ == '__main__':
    cfg = ConfigParser()
    cfg.read('AppendString.ini')
    cfg.sections()
    book = load_workbook(filename=cfg.get('production', "excelFile"), read_only=True)
    sheet_name = cfg.get('production', "sheet_name")
    sheet = book.get_sheet_by_name(sheet_name)

    # 有数据的第一行
    startRowIndex = cfg.getint('production', 'startRowIndex')
    # 有数据的最后一行
    endRowIndex = cfg.getint('production', 'endRowIndex')
    # 有数据的第一列的列标题
    startColumnTitle = cfg.get('production', 'startColumnTitle')
    startColumnTitleIndex = -1
    # 有数据的最后一列的列标题
    endColumnTitle = cfg.get('production', 'endColumnTitle')
    endColumnTitleIndex = -1
    # 列标题在哪一行
    columnTitleRowIndex = cfg.getint('production', 'columnTitleRowIndex')
    # key 哪一列
    keyColumnTitle = cfg.get('production', 'keyColumnTitle')
    keyColumnIndex = -1

    # 找哪些 key
    keyArray = json.loads(cfg.get("production", "keyArray"))

    # 算出有数据的最后一列的列索引，[1, 100)，左闭右开
    for i in range(1, 100):
        columnTitle = sheet.cell(columnTitleRowIndex, i).value
        if keyColumnTitle == columnTitle:
            keyColumnIndex = i
            break
    if keyColumnIndex == -1:
        print("找不到列标题为 {} 的列".format(keyColumnTitle))
        sys.exit()

    # 算出有数据的最后一列的列索引，[1, 100)，左闭右开
    for i in range(1, 100):
        columnTitle = sheet.cell(columnTitleRowIndex, i).value
        if startColumnTitle == columnTitle:
            startColumnTitleIndex = i
            break
    if startColumnTitleIndex == -1:
        print("找不到列标题为 {} 的列".format(startColumnTitle))
        sys.exit()

    # 算出有数据的最后一列的列索引，[1, 100)，左闭右开
    for i in range(1, 100):
        columnTitle = sheet.cell(columnTitleRowIndex, i).value
        if endColumnTitle == columnTitle:
            endColumnTitleIndex = i
            break
    if endColumnTitleIndex == -1:
        print("找不到列标题为 {} 的列".format(endColumnTitle))
        sys.exit()

    enData = []
    arData = []
    deData = []
    elData = []
    esData = []
    frData = []
    inData = []
    itData = []
    iwData = []
    jaData = []
    koData = []
    nlData = []
    plData = []
    ptData = []
    ruData = []
    svData = []
    thData = []
    trData = []
    zhData = []
    map = {
        "en": enData,
        "ar": arData,
        "de": deData,
        "el": elData,
        "es": esData,
        "fr": frData,
        "in": inData,
        "it": itData,
        "iw": iwData,
        "ja": jaData,
        "ko": koData,
        "nl": nlData,
        "pl": plData,
        "pt": ptData,
        "ru": ruData,
        "sv": svData,
        "th": thData,
        "tr": trData,
        "zh": zhData,
    }
    # range 左闭右开
    for rowIndex in range(startRowIndex, endRowIndex + 1):
        key = sheet.cell(rowIndex, keyColumnIndex).value
        if key not in keyArray:
            continue
        for columnIndex in range(startColumnTitleIndex, endColumnTitleIndex + 1):
            columnTitle = sheet.cell(columnTitleRowIndex, columnIndex).value
            # 改行为需要添加的翻译
            for kv in map:
                if kv in columnTitle.lower():
                    stringValue = sheet.cell(rowIndex, columnIndex).value
                    map[kv].append('<string name="{}">{}</string>'.format(key, stringValue))
                    break

    androidProjectAbsDir = cfg.get('production', 'androidProjectAbsDir')
    ########## 把新增的翻译 append 到 strings.xml 文件 [开始] ##########
    for kv in map:
        if map[kv] == []:
            print("{} 为空".format(kv))
        else:
            if kv == "en":
                file = open("{}/values/strings.xml".format(androidProjectAbsDir), 'r')
            else:
                file = open("{}/values-{}/strings.xml".format(androidProjectAbsDir, kv), 'r')

            fileContent = file.read()
            file.close()
            searchResult = re.search(r'</\s*resources\s*>', fileContent)
            if searchResult:
                searchStartIndex = searchResult.span()[0]
                searchEndIndex = searchResult.span()[1]
                fileContent = fileContent[0:searchStartIndex]
                for string in map[kv]:
                    itemKeyValueFinder = re.search(r'<string\s+name\s*=\s*"([^"]+?)"\s*>([\s\S]+?)</string\s*>', string)

                    fileContent = "{}\n{}".format(fileContent, string)

                fileContent = "{}\n</resources>".format(fileContent)
            # 把 append 好的文件内容写到原文件中
            if kv == "en":
                file = open("{}/values/strings.xml".format(androidProjectAbsDir), 'w')
            else:
                file = open("{}/values-{}/strings.xml".format(androidProjectAbsDir, kv), 'w')
            file.write(fileContent)
            file.close()
    ########## 把新增的翻译 append 到 strings.xml 文件 [结束] ##########
